#include "ULCore_Serial.h"
#include "UL_Tools.h"
#include <iomanip>

static void initSerial(ULC_Serial &serial)
{
	serial.sn = 0;
	memset(serial.extraData, 0, sizeof(int) * EXTRA_DATA_SIZE);
	memset(&serial.top, 0, sizeof(struct hitsAndPrize) * 6);
	serial.repeatedRoot = serial.nextRepeatedSerial = NULL;
	serial.actualOutBalls.DisableOutputBlue();
}

ULC_Serial::ULC_Serial()
{
	initSerial(*this);
}

//Example lineBuffer:
// 2012095 2012-08-14 17 24 27 28 29 30 02 24 29 17 27 28 30 324870412 476949363 3 9886677 92 239022 1161 3000 64836 200 1245851 10 1139552     5 5
//Format should be %d %s(serial number and date) %d %d %d %d %d %d %d(sorted reds and blue) %d %d %d %d %d %d(reds in out orders) %d %d(extra data) %d %d(top) %d %d(second) %d %d(third) %d %d(fourth) %d %d(fifth) %d %d(sixth)
int ULC_Serial::ParseLineBuffer(const char *lineBuffer)
{
	int tmpReds[6];
	int tmpBlue;
	int tmpRedsOut[6];

	if (lineBuffer){
		sscanf(lineBuffer, "%d %s %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d", 
					&sn, date, tmpReds, tmpReds + 1, tmpReds + 2,
				tmpReds + 3, tmpReds + 4, tmpReds + 5, &tmpBlue, tmpRedsOut, tmpRedsOut + 1, tmpRedsOut + 2,
		     		tmpRedsOut + 3, tmpRedsOut + 4, tmpRedsOut + 5, extraData, extraData + 1,
				&top.hits, &top.prize, &second.hits, &second.prize, &third.hits, &third.prize,
				&fourth.hits, &fourth.prize, &fifth.hits, &fifth.prize, &sixth.hits, &sixth.prize);
#ifdef ULC_SERIAL_DEBUG
		{
			cout << __func__ << endl;
			cout << lineBuffer << endl;
			cout << "tmpReds: " << endl;
			for (int i = 0; i < 6; i++){
				cout << tmpReds[i] << " ";
			}

			cout << endl;
		}
#endif	
		sortedBalls.SetNumbers(tmpReds, tmpBlue);
#ifdef ULC_SERIAL_DEBUG
		cout << "----After SetNumbers() " << sortedBalls;
#endif
		actualOutBalls.SetNumbers(tmpRedsOut, 0);

		return 0;
	}

	return -1;
}

ostream& operator<<(ostream &os, const ULC_Serial &serial)
{
	os << endl << "-----Union Lotto Serial " << serial.sn << "-----" <<endl;
	os << "Date: " << serial.date << endl;
	os << "Sorted numbers: ";
	os << serial.sortedBalls;
	os << "Out numbers: ";
	os << serial.actualOutBalls;
	os << left;
	os << setw(10) << serial.top.hits << " people won top    prize(RMB " << serial.top.prize << ")" << endl;
	os << setw(10) << serial.second.hits << " people won second prize(RMB " << serial.second.prize << ")" << endl;
	os << setw(10) << serial.third.hits << " people won third  prize(RMB " << serial.third.prize << ")" << endl;
	os << setw(10) << serial.fourth.hits << " people won fourth prize(RMB " << serial.fourth.prize << ")" << endl;
	os << setw(10) << serial.fifth.hits << " people won fifth  prize(RMB " << serial.fifth.prize << ")" << endl;
	os << setw(10) << serial.sixth.hits << " people won sixth  prize(RMB " << serial.sixth.prize << ")" << endl;
	os << "------------------------------------" << endl;

	return os;
}
